package cn.cj.erp.modules.login.controller;

import cn.cj.erp.bo.system.SysUserBo;
import cn.cj.erp.common.security.security.user.LoginUser;
import cn.cj.erp.common.security.security.utils.SecurityUtils;
import cn.cj.erp.common.vo.login.PasswordChangeVo;
import cn.cj.erp.common.vo.login.ProfileInfo;
import cn.cj.erp.modules.common.controller.AbstractController;
import cn.cj.erp.service.SysProfileService;
import cn.cj.erp.common.enums.LogBusinessTypeEnum;
import cn.cj.erp.common.http.Result;
import cn.cj.erp.common.security.annotation.Log;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 个人信息 业务处理
 * @author chenjian
 */
@Validated
@RestController
@RequestMapping("/system/profile")
public class SysProfileController extends AbstractController {
    @Resource
    private SysProfileService sysProfileService;

    /**
     * 个人信息
     */
    @GetMapping("/info")
    public Result<ProfileInfo> profile() {
        return Result.ok(sysProfileService.profile(SecurityUtils.getLoginUser().getUser()));
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = LogBusinessTypeEnum.UPDATE)
    @PostMapping("/update")
    public Result<Boolean> updateProfile(@RequestBody SysUserBo user) {
        //获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserBo sysUserBo = loginUser.getUser();
        user.setUsername(sysUserBo.getUsername());
        Result<Boolean> result = sysProfileService.updateProfile(user);
        if (result.isError()) {
            return Result.ok(false);
        }

        // 更新缓存用户信息
        sysUserBo.setName(user.getName());
        sysUserBo.setPhone(user.getPhone());
        sysUserBo.setEmail(user.getEmail());
        sysUserBo.setSex(user.getSex());
        tokenService.setLoginUser(loginUser);
        return Result.ok(true);
    }

    /**
     * 修改登录用户密码
     */
    @PostMapping("/password")
    @Log(title = "个人信息", businessType = LogBusinessTypeEnum.UPDATE)
    public Result<Boolean> password(@Valid @RequestBody PasswordChangeVo vo) {
        vo.setUserId(SecurityUtils.getLoginUser().getUserId());
        return Result.update(sysProfileService.password(vo));
    }
}
